package com.ftp.web.spider.service.nettyclinet;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.springframework.beans.factory.annotation.Autowired;


public class NettyClinet {

    private EventLoopGroup bossLoopGroup=new NioEventLoopGroup();

    @Autowired
    private NettyClinetHandler nettyClinetHandler;

    private Bootstrap clinetBootstrap=new Bootstrap();

    public void openClient() throws InterruptedException {
        clinetBootstrap.group(bossLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingResolver(null)));
                        pipeline.addLast(new ObjectEncoder());
                        pipeline.addLast(new NettyClinetHandler());
                    }
                });

        ChannelFuture future = clinetBootstrap.connect("127.0.0.1", 9091).sync();
        if(future.isSuccess()){
            System.out.println("连接成功");
        }else {
            System.out.println("连接失败");
        }
    }
}
